//
//  MyLog.m
//  AIM
//
//  Created by user10 on 2017/9/27.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "MyLog.h"
@interface MyLog ()

@property (nonatomic , strong)NSString *logPath;

@end
@implementation MyLog

static MyLog *myLogManage = nil;
+ (instancetype)shareMyLog{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        myLogManage = [[MyLog alloc]init];
        [myLogManage creatPath];
        
    });
    return myLogManage;
}

- (void)creatPath{
    //设定文件路径 ／Document／test
    NSString * logPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/test"];
    _logPath = logPath;
    NSLog(@"%@------path",_logPath);
    //创建路径
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:_logPath]) {
        [manager createDirectoryAtPath:logPath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
}

- (void)addWithOperation:(NSString *)operation type:(NSString *)type name:(NSString *)name{
    
    NSDate *date = [NSDate date]; // 获得时间对象
    
    NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
    
    [forMatter setDateFormat:@"HH-mm-ss yyyy-MM-dd"];
    
    NSString *dateStr = [forMatter stringFromDate:date];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userStr = [user objectForKey:@"TANTO_CD"];
    //获取文件中已存在的内容（因为直接写入本地会覆盖掉之前文件的内容，所以在写入前先获取，做好字符串拼接之后再写入文件）
    NSString * pure_contant = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/test_log.txt",_logPath] encoding:NSUTF8StringEncoding error:NULL];
    //--要添加的内容--
     NSString * current_contant = [NSString stringWithFormat:@"%@---%@----%@-------——-%@------%@ \n",dateStr,userStr,operation,type,name];
    
     NSString * log;
         if (pure_contant){
             log = [pure_contant stringByAppendingString:current_contant];
         }else{
             NSString *headerStr = @"       time           user     operation       type      name\n";
//             log = current_contant;
             log = [NSString stringWithFormat:@"%@%@",headerStr,current_contant];
         }
    
     //将内容写入/Document/test/test_log.txt文件中
     [log writeToFile:[NSString stringWithFormat:@"%@/test_log.txt",_logPath] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
     
    
}

@end
